package com.koushikdutta.ion.loader;

import android.content.Context;
import android.net.Uri;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.stream.InputStreamDataEmitter;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Loader.LoaderEmitter;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import java.io.InputStream;

public class AssetLoader extends StreamLoader {
    public Future<BitmapInfo> loadBitmap(Context context, Ion ion, String key, String uri, int resizeWidth, int resizeHeight, boolean animateGif) {
        if (uri.startsWith("file://android_asset/")) {
            return super.loadBitmap(context, ion, key, uri, resizeWidth, resizeHeight, animateGif);
        }
        return null;
    }

    protected InputStream getInputStream(Context context, String uri) throws Exception {
        return context.getAssets().open(Uri.parse(uri).getPath().substring(1));
    }

    public Future<DataEmitter> load(Ion ion, AsyncHttpRequest request, FutureCallback<LoaderEmitter> callback) {
        if (!request.getUri().getScheme().startsWith("file://android_asset/")) {
            return null;
        }
        final Future<DataEmitter> ret = new InputStreamDataEmitterFuture();
        final Ion ion2 = ion;
        final AsyncHttpRequest asyncHttpRequest = request;
        final FutureCallback<LoaderEmitter> futureCallback = callback;
        ion.getHttpClient().getServer().post(new Runnable() {
            public void run() {
                try {
                    InputStream stream = ion2.getContext().getContentResolver().openInputStream(Uri.parse(asyncHttpRequest.getUri().toString()));
                    if (stream == null) {
                        throw new Exception("Unable to load content stream");
                    }
                    int available = stream.available();
                    InputStreamDataEmitter emitter = new InputStreamDataEmitter(ion2.getHttpClient().getServer(), stream);
                    ret.setComplete((Object) emitter);
                    futureCallback.onCompleted(null, new LoaderEmitter(emitter, (long) available, 1, null, null));
                } catch (Exception e) {
                    ret.setComplete(e);
                    futureCallback.onCompleted(e, null);
                }
            }
        });
        return ret;
    }
}
